package com.spring_shiro.shirotest;

import com.spring_shiro.model.UserMsg;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
//@RequestMapping("/user")
public class ShiroTest {

    @GetMapping("/user/shiroGetTest")
    @RequiresRoles("user")
    public String ShiroGetTest(){

        return "能看到ShiroGetTest这个内容";
    }

    @GetMapping("/toLogin")
    public String toLogin(){
        return "请登录";
    }

    @PostMapping("/login")
    public String login(@RequestBody UserMsg userMsg){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userMsg.getUserName(), userMsg.getPassWord());
        try{
            subject.login(usernamePasswordToken);
            System.out.println("principal-2====="+subject.getPrincipal());
            return "登录成功";
        }catch (UnknownAccountException a){
            return "用户名错误";

        }catch (IncorrectCredentialsException e){
            return "密码错误";
        }

    }
}
